<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>删除</button>
    <table border="1">
      <thead>
        <tr>
          <th><input type="checkbox" /></th>
          <th>编号</th>
          <th>姓名</th>
          <th>性别</th>
          <th>年龄</th>
          <th>邮箱</th>
          <th>手机</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="tbody"></tbody>
    </table>
    <script>
      const users = [
        {
          id: 1,
          name: "jack",
          age: 20,
          gender: "1",
          email: "jack@qq.com",
          phone: "1818865444",
        },
        {
          id: 2,
          name: "lili",
          age: 20,
          gender: "1",
          email: "jack@qq.com",
          phone: "1818865444",
        },
        {
          id: 3,
          name: "lucy",
          age: 20,
          gender: "1",
          email: "jack@qq.com",
          phone: "1818865444",
        },
      ];

      // 将"数组/对象"数据转成"表格行"字符串
      function render(data) {
        return data
          .map(
            (el) => `
            <tr>
                <td><input type="checkbox" /></td>
                <td>${el.id}</td>
                <td>${el.name}</td>
                <td>${el.gender}</td>
                <td>${el.age}</td>
                <td>${el.email}</td>
                <td>${el.phone}</td>
                <td><button data-action="remove" data-id="${el.id}">删除</button></td>
            </tr>
            `
          )
          .join("");
      }

      tbody.innerHTML = render(users);

      document.onclick = function (e) {
        const action = e.target.dataset.action;
        if (action === "remove") {
          // 删除提示
          if (confirm("确定删除？") === false) return;
          /*
            删除
            1. 删除谁：获取当前数据的ID
            2. 同步界面，数据（users）发生变化，视图也要一起发生变化（table）
            */
          // 获取数据的id
          let id = e.target.dataset.id;
          // 获取索引
          let index = users.findIndex((el) => el.id === id);
          // 删除数据
          users.splice(index, 1);
          // 重新渲染
          tbody.innerHTML = render(users);
        }
      };
    </script>
  </body>
</html>
